<template>
    <div class="wrap">
        <div id="container">
            <!-- 定义一个表格元素 -->
            <section class="detail-header">
                <div class="col-sm-12 console-title">
                    <h5 class="">实例管理</h5>
                    <div class="stayRight ">
                        <el-button @click="refreshData()">刷新</el-button>
                        <el-button type="primary" @click="updateInstance()">创建实例</el-button>
                    </div>
                    
                </div>
            </section>
            <section class="searchBar">
                <div class="form-inline">
                    <div class="pull-left">
                        <div class="searchSel">
                            <el-select v-model="ins.domain" filterable  placeholder="模块">
                                <el-option v-for="item in domains.dataArr" :key="item.id" :value="item.id" :label="item.name">
                                </el-option>
                            </el-select>
                        </div>
                        <div class="searchSel">
                            <el-select v-model="ins.tag" filterable  placeholder="标签">
                                <el-option v-for="item in tags.dataArr" :key="item.id" :value="item.id" :label="item.name">
                                </el-option>
                            </el-select>
                        </div>
                         <!-- 实例类型选择 -->
                        <div class="searchIpt">
                            <el-input v-model="ins.searchName" placeholder="请输入要搜索的关键字"></el-input>
                        </div>
                        <div class="searchbtn">
                            <el-button @click="getInstances(1)">搜索</el-button>
                        </div>
                    </div>
                </div>
            </section>
            <section class="tableMain">
                <el-table :data="ins.dataArr" border style="width: 100%">
                    <el-table-column prop="name" label="实例名称" > </el-table-column>
                    <el-table-column prop="domain" label="实例所属模块" :formatter="formatDomain"> </el-table-column>
                    <el-table-column prop="ip" label="ip地址"> </el-table-column>
                    <el-table-column prop="config" label="实例配置" :formatter="formatConfig"> </el-table-column>
                    <el-table-column prop="type" label="实例类型" :formatter="formatType"> </el-table-column>
                    <el-table-column prop="status" label="实例状态">
                      <template scope="scope">
                        <el-tag :type="scope.row.status == 1 ? 'success' : 'gray'" close-transition>{{scope.row.status == 1 ? '启用' : '停用'}}</el-tag>
                      </template>
                    </el-table-column>
                    <el-table-column label="操作" >
                      <template scope="scope">
                        <el-button v-if="scope.row.status == 1" size="small" type="text" @click="disableIns(scope.row.id)">停用</el-button> 
                        <el-button v-else size="small" type="text" @click="enableIns(scope.row.id)">启用</el-button>
                        <el-button size="small" type="text" @click="updateInstance(scope.row.id)">编辑</el-button> 

                        <!-- <el-dropdown trigger="click" @command="handleCommand">
                          <el-button type="primary" size="small">
                            管理 <i class="el-icon-caret-bottom el-icon-right"/>
                          </el-button>
                          <el-dropdown-menu slot="dropdown">
                            <el-dropdown-item :command="'this.enableIns('+scope.row.id+')'">启用</el-dropdown-item>
                            <el-dropdown-item :command="'this.disableIns('+scope.row.id+')'">停用</el-dropdown-item>
                            <el-dropdown-item divided :command="'this.updateInstance('+scope.row.id+')'">编辑信息</el-dropdown-item>
                          </el-dropdown-menu>
                        </el-dropdown> -->
                      </template>
                    </el-table-column>
                </el-table>
                <div class="pageSIzeblock">
                    <div class="pullright">
                        <el-pagination @size-change="handleSizeChange"  @current-change="handleCurrentChange" :current-page="ins.currPage" :page-sizes="[10, 20, 50, 100]" :page-size="ins.pageSize" layout="total, sizes, prev, pager, next, jumper" :total="ins.totalCount">
                        </el-pagination>
                    </div>
                </div>
            </section>
            
            <el-dialog :title="updateTitle" :visible.sync="updateDialogVislble" class="customDialog team" :lock-scroll="false" :before-close="colseDialog">
                <div class="scoreContainer tagCategory">
                    <el-form :model="updateForm" :rules="updateRules" ref="updateForm" label-width="120px" class="demo-updateForm">
                        <el-form-item label="实例名称" prop="name">
                          <el-input v-model="updateForm.name"></el-input>
                        </el-form-item>
                        <el-form-item label="ip地址" prop="ip">
                          <el-input v-model="updateForm.ip"></el-input>
                        </el-form-item>
                        <el-form-item label="实例cpu" prop="cpu">
                          <el-input v-model="updateForm.cpu" type="number"></el-input>
                        </el-form-item>
                        <el-form-item label="实例内存" prop="memory">
                          <el-input v-model="updateForm.memory" type="number"></el-input>
                        </el-form-item>
                        <el-form-item label="所属模块" prop="domain" @change="updateGroupid">
                          <el-select v-model="updateForm.domainId" filterable  placeholder="模块">
                              <el-option v-for="item in domains.data" :key="item.id" :value="item.id" :label="item.name">
                              </el-option>
                          </el-select>
                        </el-form-item>
                        <el-form-item label="实例类型" prop="type">
                          <el-select v-model="updateForm.typeId" filterable  placeholder="标签">
                              <el-option v-for="item in types.data" :key="item.id" :value="item.id" :label="item.name">
                              </el-option>
                          </el-select>
                        </el-form-item>
                        <el-form-item label="实例标签" prop="tag">
                          <el-select v-model="updateForm.tagIds" multiple filterable allow-create default-first-option @change="updateTag" placeholder="请选择标签" >
                              <el-option v-for="item in tags.data" :key="item.id" :value="item.id" :label="item.name">
                              </el-option>
                          </el-select>
                          可自行输入按Enter键添加
                        </el-form-item>
                        <el-form-item label="实例状态" prop="status">
                          <el-select v-model="updateForm.status" placeholder="请选择">
                            <el-option 
                                v-for="item in ins.status" 
                                :key="item.id" 
                                :value="item.id" 
                                :label="item.text">
                            </el-option>
                          </el-select>
                        </el-form-item>
                    </el-form>
                </div>

                <span slot="footer" class="dialog-footer">
                    <div class="aar-gap">
                        <div class="aar-gap-line-b">
                            <div class="aar-gap-line"></div>
                        </div>
                    </div>
                  <el-button @click="cancelSubmit('updateForm')">取 消</el-button>
                  <el-button type="primary" @click="creatSubmit('updateForm')">确 定</el-button>
                </span>
            </el-dialog>

        </div>
    </div>
</template>
<script>
import { save, update, updateStatus, queryInstances, queryAllTypes, queryMyDomains, queryMyTags, saveBatchTag, check } from '@/api/instanceData'
import { Loading } from 'element-ui'
import { parseTime } from '@/utils/index'
export default {
  data() {
    return {
      ins: {
        dataArr: [],
        currPage: 1,
        pageSize: 10,
        totalCount: 0,
        type: '',
        domain: '',
        tag: '',
        searchName: '',
        selection: [],
        status: [
          {
            id: '1',
            text: '开启'
          },
          {
            id: '0',
            text: '关闭'
          }
        ]
      },
      types: {
        dataArr: [],
        map: {}
      },
      domains: {
        dataArr: [],
        map: {}
      },
      tags: {
        dataArr: [],
        map: {},
        reMap: {}
      },
      updateTitle: '编辑实例',
      updateDialogVislble: false,
      updateForm: {
        name: '',
        ip: '',
        cpu: '',
        memory: '',
        typeId: '',
        domainId: '',
        groupid: '',
        tagIds: [],
        status: '1',
        dutyMan: ''
      },
      updateRules: {
        name: [
          { validator: this.checkName, trigger: 'blur' }
        ],
        ip: [
          { validator: this.checkIP, trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getInstances(1)
    this.getTypes()
    this.getDomains()
    this.getTags()
  },
  methods: {
    refreshData() {
      this.ins.type = ''
      this.ins.domain = ''
      this.ins.tag = ''
      this.ins.searchName = ''
      this.getInstances(1)
    },
    getInstances(currPage) {
      this.ins.currPage = currPage
      var loadId = Loading.service({ text: '加载中，请稍等' })
      var listQuery = { typeId: this.ins.type, domainId: this.ins.domain, tagId: this.ins.tag, keyword: this.ins.searchName, currPage: this.ins.currPage, pageSize: this.ins.pageSize }
      queryInstances(listQuery).then(response => {
        this.ins.dataArr = response.data.page.list
        loadId.close()
        this.ins.totalCount = response.data.page.totalCount
      }).catch(_ => {
        loadId.close()
      })
    },
    getTypes() {
      queryAllTypes().then(response => {
        const arr = []
        arr.push({ id: '', name: '全部类型' })
        for (var i in response.data.rows) {
          arr.push(response.data.rows[i])
          this.types.map[response.data.rows[i].id] = response.data.rows[i].name
        }
        this.types.dataArr = arr
        this.types.data = response.data.rows
      }).catch(_ => {
      })
    },
    getDomains() {
      queryMyDomains().then(response => {
        const arr = []
        arr.push({ id: '', name: '全部模块' })
        for (var i in response.data.rows) {
          arr.push(response.data.rows[i])
          this.domains.map[response.data.rows[i].id] = response.data.rows[i].name
        }
        this.domains.dataArr = arr
        this.domains.data = response.data.rows
      }).catch(_ => {
      })
    },
    getTags() {
      queryMyTags().then(response => {
        const arr = []
        arr.push({ id: '', name: '全部标签' })
        for (var i in response.data.rows) {
          arr.push(response.data.rows[i])
          this.tags.map[response.data.rows[i].id] = response.data.rows[i].name
        }
        this.tags.dataArr = arr
        this.tags.data = response.data.rows
      }).catch(_ => {
      })
    },
    formatTime(row, column) {
      if (row.updateTime) {
        return parseTime(row.updateTime)
      }
      return ''
    },
    formatDomain(row, column) {
      return this.domains.map[row.domainId]
    },
    formatType(row, column) {
      return this.types.map[row.typeId]
    },
    formatConfig(row, column) {
      return 'cpu:' + row.cpu + '\n 内存:' + row.memory
    },
    checkName(rule, value, callback) {
      if (callback) {
        if (!value) {
          callback(new Error('实例名不能为空'))
        } else {
          var listQuery = { id: this.updateForm.id, name: value }
          check(listQuery).then(response => {
            if (response.data.msg) {
              callback(new Error(response.data.msg))
            }
            callback()
          })
        }
      }
    },
    checkIP(rule, value, callback) {
      if (callback) {
        if (!value) {
          callback(new Error('IP不能为空'))
        } else {
          var reg = /^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$/
          if (!reg.test(value)) {
            callback(new Error('IP地址格式不正确'))
          }
          var listQuery = { id: this.updateForm.id, ip: value }
          check(listQuery).then(response => {
            if (response.data.msg) {
              callback(new Error(response.data.msg))
            }
            callback()
          })
        }
      }
    },
    handleCommand(data) {
      // eval(data)
    },
    disableIns(id) {
      this.$confirm('是否停用该实例？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const data = { id: id, status: 0 }
        updateStatus(data).then(response => {
          this.getInstances(1)
        })
      }).catch(() => {
      })
    },
    enableIns(id) {
      this.$confirm('是否启用该实例？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }).then(() => {
        const data = { id: id, status: 1 }
        updateStatus(data).then(response => {
          this.getInstances(1)
        })
      }).catch(() => {
      })
    },
    /* delInstance(id) {
      this.$confirm('确认删除该实例吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteById(id).then(response => {
          this.getInstances(1)
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除！'
        })
      })
    },
    handleSelectionChange(val) {
      this.ins.selection = val
    }, */
    handleCurrentChange(currPage) {
      this.ins.currPage = currPage
      this.getInstances(currPage)
    },
    handleSizeChange(pageSize) {
      this.ins.pageSize = pageSize
      this.getInstances(1)
    },
    updateInstance(id) {
      if (id) {
        this.updateTitle = '修改实例信息'
        for (var a in this.ins.dataArr) {
          if (this.ins.dataArr[a].id === id) {
            this.updateForm = JSON.parse(JSON.stringify(this.ins.dataArr[a]))
            break
          }
        }
      } else {
        this.updateForm.id = null
        this.updateTitle = '添加实例'
      }
      this.updateDialogVislble = true
    },
    /* queryURLs(kw, cb) {
      var keywordQuery = { column: 'url', plat: this.selectedPlat, keyword: kw }
      const res = []
      queryKeywords(keywordQuery).then(response => {
        if (response.data.keywords) {
          response.data.keywords.forEach(function(ele) {
            res.push({ value: ele })
          })
          cb(res)
        }
      }).catch(_ => {
      })
    },
    queryTags(kw, cb) {
      var keywordQuery = { column: 'tag', plat: this.selectedPlat, keyword: kw, ids: this.selectedIds }
      const res = []
      queryKeywords(keywordQuery).then(response => {
        response.data.keywords.forEach(function(ele) {
          res.push({ value: ele })
        })
        cb(res)
      }).catch(_ => {
      })
    },*/
    updateTag() {
      var beSaveTag = []
      for (var i in this.updateForm.tagIds) {
        var tag = this.updateForm.tagIds[i]
        if (typeof tag === 'string') {
          beSaveTag.push(tag)
        }
      }
      if (beSaveTag.length) {
        var loadId = Loading.service({ text: '保存中' })
        saveBatchTag({ tags: beSaveTag }).then(response => {
          const arr = []
          arr.push({ id: '', name: '全部标签' })
          for (var i in response.data.rows) {
            arr.push(response.data.rows[i])
            this.tags.map[response.data.rows[i].id] = response.data.rows[i].name
            this.tags.reMap[response.data.rows[i].name] = response.data.rows[i].id
          }
          this.tags.dataArr = arr
          this.tags.data = response.data.rows
          for (var j in this.updateForm.tagIds) {
            var tag = this.updateForm.tagIds[j]
            if (typeof tag === 'string') {
              this.updateForm.tagIds[j] = this.tags.reMap[this.updateForm.tagIds[j]]
            }
          }
          loadId.close()
        }).catch(_ => {
          loadId.close()
        })
      }
    },
    updateGroupid(domainId) {
      if (domainId) {
        for (var a in this.domains.data) {
          if (this.domains.data[a].id === domainId) {
            this.updateForm.groupid = this.domains.data[a].groupid
            break
          }
        }
      }
    },
    cleanData() {
      this.ins.type = ''
      this.ins.domain = ''
      this.ins.tag = ''
      this.ins.searchName = ''
      this.updateForm = {
        name: '',
        ip: '',
        cpu: '',
        memory: '',
        typeId: '',
        domainId: '',
        groupid: '',
        tagIds: [],
        status: '1',
        dutyMan: ''
      }
    },
    colseDialog(done) {
      this.$confirm('改动未保存,是否关闭？')
        .then(_ => {
          this.cleanData()
          done()
        })
        .catch(_ => {})
    },
    cancelSubmit(formName) {
      var _this = this
      const done = function() {
        _this.cleanData()
        _this.updateDialogVislble = false
      }
      this.colseDialog(done)
    },
    creatSubmit(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          var loadId = Loading.service({ text: '正在保存' })
          var jsonData = this.updateForm
          var _this = this
          const resetTable = function() {
            _this.updateDialogVislble = false
            _this.cleanData()
            _this.getInstances(1)
            _this.getTags()
          }
          if (this.updateForm.id) {
            update(jsonData).then(response => {
              loadId.close()
              this.$message({
                showClose: true,
                message: '修改成功',
                type: 'success'
              })
              resetTable()
            }).catch(_ => {
              loadId.close()
            })
          } else {
            save(jsonData).then(response => {
              loadId.close()
              this.$message({
                showClose: true,
                message: '保存成功！',
                type: 'success'
              })
              resetTable()
            }).catch(_ => {
              loadId.close()
            })
          }
        }
      })
    }
  }
}
</script>


<style lang="scss">
.el-table .warning-row {
    background: #dd9999;
}
.el-table .info-row {
    background: #c9e5f5;
}
.detail-header{
    padding: 0 15px;
    margin-bottom: 10px;
    overflow: hidden;
    .console-title{
        padding: 16px 0px;
        min-height: 70px;
        border-bottom: 1px solid #eee;
        position: relative;
        h5{
            display: inline-block;
            text-indent: 8px;
            border-left: 2px solid #88B7E0;
            margin: 8px 0;
            margin-right: 8px;
            vertical-align: top;
        }
        .stayRight{
            position: absolute;
            top: 15px;
            right: 0;
            overflow: hidden;
            .refresh{
                float: left;
                margin-right: 10px;
                color: #333;
                border: 1px solid #ddd;
                background-color: #F7F7F7;
            }
            .creatSite{
                float: left;
            }
        }
    }
}
.searchSel{
    width: 150px;
    display: inline-block;
}
.searchIpt{
    width: 350px;
    display: inline-block;
}
.searchbtn{
    width: 100px;
    display: inline-block;
}
.searchBar{
    padding: 0 10px;
}
.tableMain{
    padding: 10px;
}
.typeform{
    display: inline;
    .form-control{
        border: none;
        padding: 0;
        box-shadow:none;
        display: inline;
        height:30px;
        width:60%;
    }
}
.spantype{
    display: inline;
}
.pageSIzeblock{
    overflow: hidden;
    padding: 10px 0;
    .pullright{
        float: right;
    }
}

.aar-gap-line{height:0;border-bottom:1px dotted #888888;display:inline-block;width:100%;}
.aar-gap-index{background:#0099cc;position:absolute;left:0;top:0;width:40px;height:40px;color:#fff;border-radius:20px;text-align:center;line-height:40px;}
.aar-gap{position:relative;height:50px;}
.aar-gap-title{margin-left:15px;font-weight:bold;font-size:20px;position:absolute;left:40px;top:12px;background:#fff;padding-right:8px;}
.aar-gap-line-c{height:40px;margin:0 0 0 120px;line-height:38px}
.aar-gap-line-b{height:40px;line-height:38px}
.instanceTypeClass .el-select{width:800px;}
.delBtn{font-weight:bold;font-size:13px;position:absolute;right:0px;top:8px;background:#fff;}
</style>


